package com.youwei.room.database

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.youwei.room.dao.ClassesDao
import com.youwei.room.dao.StudentsDao
import com.youwei.room.entity.Classes
import com.youwei.room.entity.Students
import net.zetetic.database.sqlcipher.SupportOpenHelperFactory


/**
 * @Author：Bin YouWei
 * @Date：2022/6/27/11:59
 * @Declaration：管理一个数据库里面的表
 */
@Database(
    entities = [Classes::class, Students::class],
    version = 2,
    exportSchema = false
)
abstract class SchoolDatabase : RoomDatabase() {
    /**
     * 调用该方法获取Dao，来调用Classes表的接口方法
     */
    abstract fun classDao(): ClassesDao
    /**
     * 调用该方法获取Dao，来调用Students表的接口方法
     */
    abstract fun studentsDao(): StudentsDao

    companion object {
        var db: SchoolDatabase ?= null

        // 单例模式的双重检查锁
        fun getDataBase(context: Context) : SchoolDatabase{
            if (db == null){
                synchronized(SchoolDatabase::class.java){
                    if (db == null){
                        // 不使用 SQLCipher 加密
                        /*db = Room.databaseBuilder(context.applicationContext, SchoolDatabase::class.java, "school")
                            // .fallbackToDestructiveMigration()
                            .allowMainThreadQueries()
                            // 添加数据迁移
                            .addMigrations(MIGRATION_1_TO_2)
                            .build()*/
                        // 使用 SQLCipher 加密
                        val factory = SupportOpenHelperFactory("school".toByteArray())
                        db = Room.databaseBuilder(context.applicationContext, SchoolDatabase::class.java, "school")
                            .openHelperFactory(factory)
                            // .fallbackToDestructiveMigration()
                            .allowMainThreadQueries()
                            // 添加数据迁移
                            .addMigrations(MIGRATION_1_TO_2)
                            .build()
                    }
                }
            }
            return db as SchoolDatabase;
        }

        // Migration实例的两个参数指的是当前版本升级到什么版本
        val MIGRATION_1_TO_2 : Migration = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                //  添加新的列使用 底层SQLite + sql 语法，其它增删改查亦是如此
                database.execSQL("alter table classes add column classesNum TEXT default 'null'")
            }
        }
    }
}